<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\library\Auth;
use fast\Random;
use think\Db;
use think\Exception;

/**
 * 课程管理
 *
 * @icon fa fa-user
 */
class Company extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';
    protected $noNeedRight = ['open','close', 'getCompany', 'card_list'];

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Company');
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->relationSearch =true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset,$limit)
                ->select();
            foreach ($list as $w=>&$v){
               $total_num = Db::name('card')->where(['company_id' => $v['id']])->count();
               $use_num = Db::name('card')->where(['company_id' => $v['id'], 'status' => 1])->count();
               $v['total_num'] = $total_num;
               $v['use_num'] = $use_num;
            }
            $result = array("total" => $count, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            try{
                Db::startTrans();

                if (strlen($params['company_code']) != 6) {
                    $this->error("公司编码需要6位数");
                }
                $where = [
                    'company_code' => $params['company_code']
                ];
                $code = $this->model->where($where)->find();
                if ($code) {
                    $this->error("该公司编码已存在");
                }
                $params['createtime'] = time();
                $params['updatetime'] = time();
                $res = $this->model->insertGetId($params);
                if ($res){
                    Db::commit();
                    $this->success();
                }
            }catch(Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids=''){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    if (strlen($params['company_code']) != 6) {
                        $this->error("公司编码需要6位数");
                    }
                    $params['updatetime'] = time();
                    $where = [
                        'company_code' => $params['company_code'],
                        'id' => ['<>', $row['id']]
                    ];
                    $code = $this->model->where($where)->find();
                    if ($code) {
                        $this->error("该公司编码已存在");
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where(['id'=>$row['id']])->delete();
        $this->success();
    }

    /**
     * 获取公司
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCompany()
    {
        $keValue = $this->request->request("keyValue");
        $name = $this->request->param('name','');
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $show_province_id = [];
            $new_where = [];
            if ($keValue) {
                $keValue = explode(',', $keValue);
                // $new_arr = array_merge($keValue,$show_province_id);
                $new_where = [
                    'id' => ['in', $keValue]
                ];
            }
            if($name){
                $new_where['title'] = ['like','%'.$name.'%'];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = Db::name('company')
                ->where($where)
                ->where($new_where)
                ->where(['is_open'=>1])
                ->count();

            $list =Db::name('company')
                ->where($where)
                ->where($new_where)
                ->where(['is_open'=>1])
                ->order('id desc')
                ->select();
            $list = collection($list)->toArray();
            $new_list = [];
            foreach ($list as $w => $v) {
                $new_data = [
                    'id' => $v['id'],
                    'title' => $v['company_name'],
                ];
                $new_list[$w] = $new_data;
            }
            $result = array("total" => $total, "list" => $new_list);
            return json($result);
        }
    }

    public function card_list($ids = null)
    {
        $ids = $ids ?: $this->request->get('id');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('会员信息不存在'));
        }
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $newWhere = ['company_id' => $ids];
            $where = [];
            $filter = $this->request->get('filter');
            $offset = $this->request->get('offset');
            $order = $this->request->get('order');
            $sort = $this->request->get('sort');
            $limit = $this->request->get('limit');
            $filter = json_decode($filter, true);
            $string = '';
            foreach ($filter as $w => $v) {
                if ($w == 'addtime') {
                    $time_arr = explode(' - ', $v);
                    $where['addtime'] = ['between', [strtotime($time_arr[0]), strtotime($time_arr[1])]];
                    //  $where_new['end_time'] = ['',$time_arr[1]];
                } else if ($w == 'status') {
                    $where[$w] = $v;
                }
            }
            $count = Db::name('card')
                ->where($where)
                ->where($newWhere)
                ->count();
            $list = Db::name('card')
                ->where($where)
                ->where($newWhere)
                ->order('id desc')
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $w => &$v) {
            }
            $result = array("total" => $count, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

}
